package com.top.art.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.top.art.annotation.PermissionLimit;
import com.top.art.tool.AuthTool;
import com.top.art.tool.JwtToken;
import com.top.art.vo.AccountInfoVO;
import com.top.art.vo.ResVO;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * The type Permission interceptor.
 *
 * @author hjh
 */
@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {


    @Resource
    private JwtToken jwtToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }

        boolean needLogin = true;
        HandlerMethod method = (HandlerMethod) handler;
        PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class);
        if (permission != null) {
            needLogin = permission.limit();
        }
        if (needLogin) {
            String token = request.getHeader("Art-Token");
            if (Strings.isNullOrEmpty(token)) {
                notLoginResponse(response);
                return false;
            }
            Claims claims = null;
            try {
                claims = jwtToken.parseToken(token);
            } catch (Exception ex) {
                wrongTokenResponse(response);
                return false;
            }
            String json = (String) claims.get("userinfo");
            AccountInfoVO accountInfo = JSONObject.parseObject(json, AccountInfoVO.class);
            request.setAttribute(AuthTool.USER_ATTR, accountInfo);
        }

        return super.preHandle(request, response, handler);
    }

    private void notLoginResponse(HttpServletResponse response) throws IOException {
        ResVO resVo = new ResVO();
        resVo.setCode(505);
        resVo.setMessage("token不存在");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(resVo));
    }

    private void wrongTokenResponse(HttpServletResponse response) throws IOException {
        ResVO resVo = new ResVO();
        resVo.setCode(506);
        resVo.setMessage("token错误");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(resVo));
    }

}
